<template>
  <div>
    <button @click="exchangeToken">兑换代币</button>
  </div>
</template>

<script>
// 一定要确保安装了 serum 和 web3.js 相关的 npm 包
import { Connection, PublicKey, Transaction, Keypair} from '@solana/web3.js';
import { Market } from '@project-serum/serum';

export default {
  name: 'SerumTrade',
  methods: {
    async exchangeToken() {
      // 初始化Solana连接
      const connection = new Connection('https://api.mainnet-beta.solana.com');
      // 创建钱包Keypair
      const secretKey = Uint8Array.from([103,121,153,211,146,129,238,63,5,211,73,172,74,183,177,212,128,30,233,51,177,77,67,212,9,162,218,22,235,173,17,233,60,175,134,135,221,156,254,84,190,70,178,41,122,82,184,17,75,34,138,130,251,81,96,25,77,140,175,49,249,35,4,190]);
      const payer = Keypair.fromSecretKey(secretKey);
      
      // Serum市场地址
      const marketAddress = new PublicKey('HWHvQhFmJB3NUcu1aihKmrKegfVxBEHzwVX6yZCKEsi1');
      //合约id
      const programId = new PublicKey('22Y43yTVxuUkoRKdm9thyRhQ3SdgQS7c7kB6UNCiaczD');
      //主网id：9wH4e2Xe22pCpwgaYPX4JPoqVzS7f9C8kNsVmzFD2ai9
        // 加载市场
        console.log("=================")
        const market = await Market.load(connection, marketAddress, {}, programId);
        console.log("================="+market)
        // 下面的参数需要根据你的需求进行调整
        const side = 'buy'; // 或 'sell'，根据实际情况
        const price = 1.5; // 你的订单价格
        const size = 1; // 你要买或卖的数量
        const orderType = 'limit'; // 限价订单    //market市价

        // 获取需要的账户
        const {orderPayerTokenAccount} =
          await market.findAccountsForMarket(connection);

        // 创建交易
        const transaction = new Transaction();

        // 添加创建订单指令到交易
        transaction.add(market.makePlaceOrderTransaction(connection, {
          owner: payer,
          payer: orderPayerTokenAccount,
          side: side,
          price: price,
          size: size,
          orderType: orderType,
        }));

        // 签名并发送交易
        const signature = await connection.sendTransaction(transaction, [payer]);

        // 确认交易
        await connection.confirmTransaction(signature, 'processed');

        console.log(`Trade executed with signature: ${signature}`);
    },
  },
};
</script>